﻿#if !SILVERLIGHT

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace System.Runtime.Serialization
{
    public static class SerializationServices
    {
        public static T RoundTrip<T>(T value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, value);

                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }

        public static T Create<T>(SerializationInfo info, StreamingContext context)
        {
            ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
                                                                   new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

            Assert.IsNotNull(constructor, "Type does not have a private or protected serialization constructor.");

            try
            {
                return (T)constructor.Invoke(new object[] { info, context });
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
    }
}

#endif // !SILVERLIGHT